package com.xiaoming.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义异步线程池配置
 *
 * @author xiaoming
 * @Date 2020/4/20
 * @blame Android Team
 */
@Slf4j
@Configuration
public class AsyncPoolConfig implements AsyncConfigurer {

    /**
     *  自定义线程池
     * @return
     */
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(10);
        // 最大线程数 核心线程用完，缓冲队列已满
        executor.setMaxPoolSize(20);
        // 缓冲队列容量
        executor.setQueueCapacity(20);
        // 最大存活时间
        executor.setKeepAliveSeconds(60);
        //线程名前缀
        executor.setThreadNamePrefix("xmAsync_");

        // 是否等待所有线程执行完毕关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时长
        executor.setAwaitTerminationSeconds(60);

        // 拒绝策略 CallerRunsPolicy
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * 定义异步任务异常处理类
     *  只会处理没有返回值的异步任务
     *  有返回值的异步任务异常由客户端实现
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }

    class AsyncExceptionHandler implements  AsyncUncaughtExceptionHandler{

        /**
         *
         * @param throwable 异步处理任务抛出异常对象
         * @param method 异常处理方法
         * @param objects 参数
         */
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
            log.info("AsyncError: {}, Method: {}, Param: {}",
                    throwable.getMessage(),
                    method.getName(),
                    JSON.toJSONString(objects));
            throwable.printStackTrace();

            //TODO 发送邮件或者短信
        }
    }
}
